import { useEffect } from 'react';
import { useTableContext } from '../context';
import { scrollToCell, scrollToCellWithDynamicHeight } from '../utils/scrollUtils';
import { TColumn } from '@/components/editable-excel-table';

export function useErrorNavigation(
    containerRef: React.RefObject<HTMLDivElement>,
    rowHeight: number,
    navigationTimeRef: React.RefObject<number>
) {
    const { state } = useTableContext();
    const columns = state.sheetData.columns as TColumn[];

    // 监听 activeCell 变化，但只在导航操作后滚动
    useEffect(() => {
        if (state.activeCell && state.errorPositions.length > 0) {
            const { rowIndex, dataIndex } = state.activeCell;
            const columnIndex = columns.findIndex((col) => col.dataIndex === dataIndex);

            // 检查是否是导航操作触发的 activeCell 变化
            // 通过检查时间戳来判断是否是最近的导航操作
            const now = Date.now();
            const lastNavigationTime = navigationTimeRef.current || 0;
            const isRecentNavigation = now - lastNavigationTime < 1000; // 1秒内的变化认为是导航

            if (columnIndex !== -1 && isRecentNavigation) {
                setTimeout(() => {
                    scrollToCell(rowIndex, columnIndex, containerRef, rowHeight, columns);
                }, 100);
            }
        }
    }, [state.activeCell, state.errorPositions, columns, rowHeight, navigationTimeRef]);
}

/**
 * 支持动态行高的错误导航 hook
 */
export function useErrorNavigationWithDynamicHeight(
    containerRef: React.RefObject<HTMLDivElement>,
    rowHeights: Map<number, number>,
    defaultRowHeight: number,
    navigationTimeRef: React.RefObject<number>
) {
    const { state } = useTableContext();
    const columns = state.sheetData.columns as TColumn[];

    // 监听 activeCell 变化，但只在导航操作后滚动
    useEffect(() => {
        if (state.activeCell && state.errorPositions.length > 0) {
            const { rowIndex, dataIndex } = state.activeCell;
            const columnIndex = columns.findIndex((col) => col.dataIndex === dataIndex);

            // 检查是否是导航操作触发的 activeCell 变化
            // 通过检查时间戳来判断是否是最近的导航操作
            const now = Date.now();
            const lastNavigationTime = navigationTimeRef.current || 0;
            const isRecentNavigation = now - lastNavigationTime < 1000; // 1秒内的变化认为是导航

            if (columnIndex !== -1 && isRecentNavigation) {
                setTimeout(() => {
                    scrollToCellWithDynamicHeight(
                        rowIndex,
                        columnIndex,
                        containerRef,
                        rowHeights,
                        defaultRowHeight,
                        columns
                    );
                }, 100);
            }
        }
    }, [state.activeCell, state.errorPositions, columns, rowHeights, defaultRowHeight, navigationTimeRef]);
}
